<template>
  <FormView
    v-model="entity"
    :title="entity.id ? '修改资产领用' : '新建资产领用'"
    :toolbar-attrs="{
      buttons: [
        'back',
        {
          save: true,
          submit: hasBtn('submit'),
          withdraw: flowContext.canWithdraw,
          reject: flowContext.canReject,
          finish: hasBtn('finish')
        }
      ]
    }"
    :toolbar-listeners="{
      save: () => saveAndStart({ title: `${userName}的资产领用单${entity.caseid}`, variables: { days: entity.days } }),
      submit: submitAudit,
      finish: () => submitAudit(),
      withdraw: () => withdrawAudit(),
      reject: () => reject()
    }">
    <FormHolder ref="form" label-width="100px" :model="entity" :disabled="entity.status === '2'">
      <FormItemGroup block-title="基本信息">
        <FormInput v-model="entity.caseid" prop="caseid" label="领用单号" disabled />
        <FormInput v-model="entity.createBy" prop="createBy" label="领用人" disabled />
        <FormInput v-model="entity.deptFullname" :span="24" prop="deptFullname" label="领用单位" disabled />
        <FormInput
          v-model="entity.userName"
          prop="userName"
          :span="12"
          label="使用人"
          placeholder="请选择使用人"
          readonly
          required>
          <template #append>
            <slot name="append">
              <ElButton type="button" style="padding-right: 10px" @click="isShowUserPicker = true"> 选择 </ElButton>
            </slot>
          </template>
        </FormInput>
        <FormInput v-model="entity.amount" prop="amount" label="总价格" disabled />
        <FormDatePicker v-model="entity.createTime" date-time label="领用时间" prop="createTime" required />

        <FormDatePicker v-model="entity.outTime" :span="12" date-time label="出库日期" prop="outTime" disabled />
        <FormItem label="领用仓库" :span="12" prop="outhouseId" label-width="100px" required>
          <VueTreeSelect
            v-model="entity.outhouseId"
            :options="dictData.warehouseTreeList"
            :disable-branch-nodes="true"
            :class="['form-tree-select', { 'is-readonly': false }]"
            :disabled="entity.status === '2' || entity.status === '3'"
            :show-count="true"
            :normalizer="normalizer"
            no-options-text="无仓库选项"
            placeholder="请选择仓库" />
        </FormItem>
        <FormItem label="房间名称" :span="12" prop="inhouseId" label-width="100px" required>
          <VueTreeSelect
            v-model="entity.inhouseId"
            :options="dictData.houseTreeList"
            :disable-branch-nodes="true"
            :class="['form-tree-select', { 'is-readonly': false }]"
            :disabled="entity.status === '2' || entity.status === '3'"
            :show-count="true"
            :normalizer="normalizer"
            no-options-text="无房屋选项"
            placeholder="请选择房屋"
            @select="onHouseNodeClick" />
        </FormItem>
        <FormSelect
          v-model="entity.inlocationId"
          :span="12"
          label="存放位置"
          :options="positionTreeList"
          filterable
          prop="inlocationId"
          required />
        <FormSelect
          v-model="entity.currencyType"
          dict-type="currency_type"
          classic
          label="货币类型"
          prop="currencyType" />
        <FormTextarea v-model="entity.explains" label="验收说明" prop="explains" rows="5" max-length="3000" />
        <ElCol :span="24">
          <FlexRow vertical-center style="padding: 10px">
            <FlexItem><span style="color: #f56c6c">*</span>领用明细-物品列表</FlexItem>
            <ElButton size="mini" type="primary" class="el-icon-circle-plus" @click="isPickerShow = true">
              添加</ElButton
            >
            <ElButton size="mini" type="primary" class="el-icon-delete" @click="deleteSelectCard"> 删除所选</ElButton>
          </FlexRow>
          <FormTable
            ref="formTable"
            v-model="entity.receiveList"
            prop="receiveList"
            required
            selection-width="60"
            placeholder="请选择物品"
            editable
            :show-summary="true"
            hide-label
            :handle-column="false"
            :columns="columns" />
        </ElCol>
      </FormItemGroup>
      <FormItemGroup :gutter="0" block-title="附件信息">
        <UploadPage
          v-if="entity.unid"
          ref="UploadPage"
          style="padding: 0"
          :unique-code="entity.unid"
          model="receive"
          classify="purchaseOrder" />
      </FormItemGroup>
    </FormHolder>
    <!-- 流程发送选择框 -->
    <FlowableHandleUserTable :visible.sync="visibleUser" :selection="true" :multiple="true" />
    <AssetCardTable
      :visible.sync="isPickerShow"
      :asset-card-id="entity.id"
      in-type="DEVICE"
      :multiple="true"
      @confirm="onConfirm" />
    <!-- 选择用户 -->
    <UserPicker
      v-if="isShowUserPicker"
      :reserve-position-on-close="false"
      close-on-click-modal
      :visible.sync="isShowUserPicker"
      @confirm="onConfirmUser" />
  </FormView>
</template>

<script>
  import { addObj, edit, putObj, createReceive } from '@/api/asset/receive'

  import FlowableHandleUserTable from '@/module/process/components/FlowableHandleUserTable.vue'
  import flowForm from '@/vue/mixin/flow-form'
  import { delReceiveList } from '@/api/asset/receivelist'
  import { getPositionListByHouseId } from '@/api/space/fyroomposition'

  export default {
    name: 'RceiveForm',
    docType: 'WF_RCEIVE',
    relativeViewId: 'ReceiveView',
    components: {
      FlowableHandleUserTable
    },
    mixins: [flowForm],
    data() {
      return {
        columns: [
          { label: '资产分类', prop: 'ctiName' },
          { label: '资产编码', prop: 'number' },
          { label: '资产名称', prop: 'name' },
          { label: '规格型号', prop: 'model' },
          { label: '计量单位', prop: 'unit' },
          { label: '金额', prop: 'amount' },
          { label: '备注', prop: 'remarks' }
        ],
        selectedRows: [],
        positionTreeList: [],
        isPickerShow: false,
        entity: {
          id: '',
          unid: 'd5e28c95-2231-46df-a2fb-88a21c9185e6',
          createId: '1187',
          createBy: 'liyue',
          type: null,
          createTime: '2023-04-25 16:25:09',
          deptId: '254',
          deptFullname: '广州海洋地质调查局',
          updateBy: null,
          updateTime: null,
          caseid: null,
          status: '0',
          userId: '',
          userName: '广州海洋地质调查局',
          userOuid: '254',
          userOufullname: '广州海洋地质调查局',
          userOuname: null,
          outTime: null,
          outhouseName: null,
          outhouseId: null,
          fullLocation: null,
          amount: null,
          currencyType: '人民币',
          detailed: null,
          explains: null,
          inhouseName: null,
          inhouseId: null,
          inlocationName: null,
          inlocationId: null,
          infullLocation: null,
          receiveList: [],
          dictOption: {
            statusList: [],
            currencyTypeList: [],
            deptTreeList: [],
            userTreeList: [],
            houseTreeList: [],
            positionTreeList: []
          }
        },
        visibleUser: false,
        isShowUserPicker: false
      }
    },
    watch: {
      entity: {
        handler(newVal, oldVal) {
          if (newVal.inhouseId) {
            this.loadPositionList(newVal.inhouseId)
          }
        },
        immediate: true,
        deep: true
      }
    },
    methods: {
      create: createReceive,
      load: edit,
      save: addObj,
      update: putObj,
      onConfirm(rows) {
        if (!this.entity.receiveList?.length) {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            this.$set(row, 'amount', row.price || undefined)
            this.entity.receiveList.push(row)
          })
        } else {
          rows.forEach(row => {
            this.$set(row, 'id', null)
            this.$set(row, 'amount', row.price || undefined)
            if (!this.entity.receiveList.find(value => value.assetCardId === row.assetCardId)) {
              this.entity.receiveList.push(row)
            }
          })
        }
      },
      deleteSelectCard() {
        this.selectedRows = this.$refs.formTable.selectedRows
        if (this.selectedRows.length === 0) {
          this.$message.warning('请选择所需要删除的物品列表')
          return
        }
        const deleteIds = this.selectedRows.filter(item => item.id > 0).map(item => item.id)
        this.$confirm(`是否确认删除"${this.selectedRows.length} "条明细数据？`, {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            if (deleteIds.length > 0) {
              delReceiveList(deleteIds)
            }
            this.entity.receiveList = this.entity.receiveList.filter(value => !this.selectedRows.includes(value))
          })
          .then(data => {
            this.$message.success('删除成功')
          })
      },
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.idCard,
          label: node.name,
          isDisabled: this.$isBlank(node.children) && !(node.affiliName === 'HOUSE'),
          children: node.children
        }
      },
      async onHouseNodeClick(node) {
        await this.loadPositionList(node.idCard)
      },
      async loadPositionList(houseId) {
        const res = await getPositionListByHouseId({ houseId })
        this.positionTreeList = res.data.data
      },
      onConfirmUser(users) {
        const user = users[0]
        this.entity.userId = user.id
        this.entity.userName = user.name
        this.entity.userOuid = user.deptId
        this.entity.userOufullname = user.deptName
      }
    }
  }
</script>
